import React, { useRef, useEffect } from "react";
import ReactDom from "react-dom";
import closeIcon from "../../../assets/close.webp";
import flvjs from "flv.js";



export default function Play(props) {
    const playRef = useRef();
    //创建元素
    const el = document.createElement("div");
    el.className = "model play-wrap";
    const { url, onClose } = props;
    useEffect(() => {
        document.querySelector("body").appendChild(el);
        if (flvjs.isSupported()) {
            var videoElement = playRef.current;
            var flvPlayer = flvjs.createPlayer({
                type: url.endsWith("mp4") ? "mp4" : "webp",
                url: url,
            });
            flvPlayer.attachMediaElement(videoElement);
            flvPlayer.load();
            flvPlayer.play();
            videoElement.addEventListener('ended', ()=>{
                //监听视频播放完毕后调用函数
                onClose();
              }, false);
        }
        return () => {
            document.querySelector("body").removeChild(el);
        };
    }, []);

    return ReactDom.createPortal(
        <div className="player">
            <div className="close" onClick={onClose}>
                <img src={closeIcon} alt="" />
            </div>
            <div className='player-content'>
            <video className='videoPlay' ref={playRef}></video>
            </div>
        </div>,
        el
    );
}
